//
//  AWNetworkTools.swift
//  WeiBo
//
//  Created by AaronWei on 2017/6/7.
//  Copyright © 2017年 AaronWei. All rights reserved.
//

import UIKit
import AFNetworking

enum RequestType {
    
    case get
    
    case post
    
}

class AWNetworkTools: AFHTTPSessionManager {

    static let sharedTools: AWNetworkTools = {
        
        let tools = AWNetworkTools()
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return tools
        
    }()
    
    fileprivate func requestData(type: RequestType, urlStr: String, params: Any?, callBack: @escaping (Any?, Error?)->()) {
        
        if type == .get {
            
            get(urlStr, parameters: params, progress: nil, success: { (_, responseObject) in
                
                callBack(responseObject, nil)
                
            }) { (_, error) in
                
                callBack(nil, error)
                
            }
            
        } else {
            
            post(urlStr, parameters: params, progress: nil, success: { (_, responseObject) in
                
                callBack(responseObject, nil)
                
            }, failure: { (_, error) in
                
                callBack(nil, error)
                
            })
            
        }
        
    }
    
}

extension AWNetworkTools {
    
    func requestStatuses(token: String,maxId: Int64, sinceId: Int64, callBack:@escaping (Any?, Error?)->()) {
        
        let urlStr = "https://api.weibo.com/2/statuses/home_timeline.json"
        
        let params: [String: Any] = ["access_token": token, "max_id": maxId, "since_id": sinceId]
        
        requestData(type: .get, urlStr: urlStr, params: params, callBack: callBack)
        
    }
    
}

extension AWNetworkTools {
    
    func requestUserInfo(token: String, uid: Int64, callBack: @escaping (Any?, Error?)->()) {
        
        let urlStr = "https://api.weibo.com/2/users/show.json"
        
        let params: [String: Any] = ["access_token": token, "uid": uid]
        
        requestData(type: .get, urlStr: urlStr, params: params, callBack: callBack)
        
    }
    
    func requestAccessToken(code: String, callBack: @escaping (Any?, Error?) -> ()) {
        
        let urlStr = "https://api.weibo.com/oauth2/access_token"
        
        let params: [String: Any] = ["client_id": AppKey, "client_secret": AppSecret, "grant_type": "authorization_code", "code": code, "redirect_uri": Redirect_Uri]
        
        requestData(type: .post, urlStr: urlStr, params: params, callBack: callBack)
        
    }
    
}
